package com.kd.d5000acquire.schedule;

import com.kd.d5000acquire.server.AppStatusServer;
import com.kd.d5000acquire.util.DMUtil;
import com.kd.d5000acquire.util.SpringUtil;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RequiredArgsConstructor
@Slf4j
//@AllArgsConstructor
@Component
public class SqlSchedule implements Runnable{
    @Autowired
    private static DMUtil dmUtil;
    @Autowired
    private static AppStatusServer appStatusServer;


    private String sql;
    private String name;
    private String definitionId;
    private Integer intervals;

    public SqlSchedule(String sql, String name, String definitionId, Integer intervals) {
        this.sql = sql;
        this.name = name;
        this.definitionId = definitionId;
        this.intervals = intervals;
        if(dmUtil == null){
            dmUtil = SpringUtil.getBean(DMUtil.class);
            appStatusServer = SpringUtil.getBean(AppStatusServer.class);
        }
    }

    @Override
    public void run() {
        try {
            String newSql = editSqlTime(sql,intervals);
            Object[] bySql = dmUtil.getBySql(newSql);
            String xml = (String) bySql[0];
            if (null == xml || xml.length() == 0){
                return;
            }
            log.info("------name------" + name);
            log.info("------sql------:\n" +newSql);
            log.info("接收到xml");
            log.info("xml为" + xml);
            appStatusServer.parsingXml(xml,name,definitionId);
        } catch (Exception e){
            log.error("执行计划异常",e);
        }
    }

    /**
     *  转换时间sql
     * @param sql
     * @param intervals
     * @return
     */
    private String editSqlTime(String sql,int intervals) {
        //获取并转换时间sql
        DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusSeconds(intervals);
        sql = sql.replace("${endTime}",endTime.format(formatter));
        sql = sql.replace("${startTime}",startTime.format(formatter));
        return sql;
    }
}
